package com.szh.htmltopdf.encrypt;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Object beforeBodyWrite(Object arg0, MethodParameter arg1, MediaType arg2,
                                  Class<? extends HttpMessageConverter<?>> arg3, ServerHttpRequest arg4,
                                  ServerHttpResponse arg5) {
        String content = "";
        try {
            content = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(arg0);
            log.info("返回报文加密前：{}", content);
            content = AesUtil.encrypt(content, "123456");
            log.info("返回报文加密后：{}", content);
        } catch (Exception e1) {
            log.error("返回报文转换异常", e1);
        }
        return content;
    }

    @Override
    public boolean supports(MethodParameter arg0, Class<? extends HttpMessageConverter<?>> arg1) {
        return true;
    }

}
